package com.wcy.app.lib.web.utils;

import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.Build;

import androidx.core.content.FileProvider;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class Fileutil {


    /**
     * 复制单个文件
     *
     * @param uri String 原文件路径+文件名 如：data/user/0/com.test/files/abc.txt
     * @return <code>true</code> if and only if the file was copied;
     * <code>false</code> otherwise
     */
    public static Uri copyFile(Activity activity, Uri uri) {
        File newPath = SuperWebX5Utils.createImageFile(activity);
        String oldPath = ImageAbsolutePath.getImageAbsolutePath(activity, uri);
        try {
            File oldFile = new File(oldPath);
            FileInputStream fileInputStream = new FileInputStream(oldFile);
            FileOutputStream fileOutputStream = new FileOutputStream(newPath);
            byte[] buffer = new byte[1024];
            int byteRead;
            while (-1 != (byteRead = fileInputStream.read(buffer))) {
                fileOutputStream.write(buffer, 0, byteRead);
            }
            fileInputStream.close();
            fileOutputStream.flush();
            fileOutputStream.close();
            Uri uri2 = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri2 = getUriFromFileForN(activity, newPath);
            } else {
                uri2 = Uri.fromFile(newPath);
            }
            return uri2;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    static Uri getUriFromFileForN(Context context, File file) {
        Uri uri2 = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri2 = FileProvider.getUriForFile(context, context.getPackageName() + ".SuperWebX5FileProvider", file);
        } else {
            uri2 = Uri.fromFile(file);
        }
        return uri2;
    }
}
